import cv2
import os
import sys
import subprocess
import numpy as np


def decode(input_video_file, output_bin_file, output_validation_file):
    # 1. 使用FFmpeg将视频解码为图像帧
    temp_dir = "temp_frames"
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    ffmpeg_cmd = [
        'ffmpeg',
        '-i', input_video_file,  # 输入视频
        '-vf', 'scale=100:100',  # 缩放视频分辨率到100x100
        os.path.join(temp_dir, 'frame_%04d.png')  # 输出图像帧
    ]

    # 执行FFmpeg命令
    subprocess.run(ffmpeg_cmd, check=True)

    # 2. 初始化变量用于存储解码后的数据
    decoded_data = bytearray()
    validation_data = bytearray()

    # 读取生成的图像帧
    frame_files = sorted(os.listdir(temp_dir))
    for frame_file in frame_files:
        frame_path = os.path.join(temp_dir, frame_file)
        # 使用OpenCV读取图像
        frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
        if frame is None:
            print(f"无法读取图像文件: {frame_path}")
            continue

        # 遍历每个像素，提取灰度值
        for y in range(frame.shape[0]):
            for x in range(frame.shape[1]):
                gray_value = frame[y, x]  # 提取像素的灰度值
                decoded_data.append(gray_value)

    # 3. 保存解码后的二进制数据
    with open(output_bin_file, "wb") as bin_file:
        bin_file.write(decoded_data)

    # 4. 读取原始的二进制文件，进行比较
    with open("in.bin", "rb") as original_bin_file:
        original_data = original_bin_file.read()
        # 验证解码的数据是否与原始数据一致
        for i in range(len(decoded_data)):
            if i < len(original_data) and decoded_data[i] == original_data[i]:
                 validation_data.append(0xFF)  # 正确
            else:
                validation_data.append(0x00)  # 错误或无效

    # 5. 保存验证结果
    with open(output_validation_file, "wb") as val_file:
        val_file.write(validation_data)

    # 清理临时图像帧
    for file in os.listdir(temp_dir):
        os.remove(os.path.join(temp_dir, file))
    os.rmdir(temp_dir)


if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python decode.py <input_video_file> <output_bin_file> <output_validation_file>")
        sys.exit(1)

    input_video_file = sys.argv[1]
    output_bin_file = sys.argv[2]
    output_validation_file = sys.argv[3]

    decode(input_video_file, output_bin_file, output_validation_file)
